<?php
/**
 * Created by PhpStorm.
 * User: luohao
 * Date: 2016/10/11
 * Time: 16:21
 */

namespace App\Service;


use App\Model\BookModel;
use App\Model\BorrowModel;

class BookService
{
    private $bookModel;
    private $borrowModel;

    /**
     * BookService constructor.
     */
    public function __construct()
    {
        $this->bookModel = new BookModel();
        $this->borrowModel = new BorrowModel();
    }

    /**
     * @param string $bookname
     * @return mixed
     */
    public function getAllBook($bookname = "")
    {
        $bookname = "%".$bookname."%";
//        dd($bookname);
        return $this->bookModel->getBook($bookname)->toArray();
    }

    /**
     * @param $bookid
     * @return string
     */
    public function getBookById($bookid)
    {
        if($this->bookModel->deleteBookById($bookid)){
            return $this->getResult(1,"删除成功");
        }
        return $this->getResult(0,"删除失败");
    }

    /**
     * @param $bookid
     * @param $userid
     * @return string
     * 借书
     */
    public function borrowBook($bookid, $userid)
    {
        if ($this->bookModel->borrowBook($bookid)) {        //第一步是改book表中的数据
            if ($this->borrowModel->addBorrow($bookid, $userid)) {      //更改成功添加borrow记录
                return $this->getResult(1,'借书成功');
            }
        }
        return $this->getResult(0,'借书失败');
    }

    /**
     * 还书
     */
    public function rentBook($bookid, $borrowid) {
        if($this->bookModel->borrowBook($bookid, 1)) {
            if($this->borrowModel->deleteBorrow($borrowid));
            return $this->getResult(1,'还书成功');
        }
        return $this->getResult(0,'还书失败');
    }


    /**
     * 续借图书
     */
    public function lastBook($borrowid)
    {
        if ($this->borrowModel->editlastBorrow($borrowid)) {
            return $this->getResult(1,'续借成功');
        }
        return $this->getResult(0,'续借失败');
    }

    /**
     * 添加图书
     */
    public function addBook($BookInfo)
    {
        if ($this->bookModel->addBook($BookInfo)) {
            return $this->getResult(1,'添加成功');
        }
        return $this->getResult(0,'添加失败');
    }

    /**
     * 修改图书
     */
    public function editBook($BookInfo)
    {
        $bookid = $BookInfo['bookid'];
        unset($BookInfo['bookid']);
//        print_r($BookInfo);
        if ($this->bookModel->updateBook($BookInfo, $bookid)) {
            return $this->getResult(1,'修改成功');
        }
        return $this->getResult(0,'修改失败');
    }

    /**
     * @param int $status
     * @param null $mag
     * @param null $data
     * @return string
     */
    private function getResult($status = 0, $mag = null, $data = null)
    {
        return json_encode(array(
            'status' => $status,
            'mag'   => $mag,
            'data'  => $data,
        ));
    }
}